from flask import Flask, request, render_template, jsonify, redirect
import hashlib

app = Flask(__name__)


@app.route('/upload', methods=['POST'])
def upload():
    # 1. 检查请求中是否包含文件和描述
    if "file" not in request.files or "description" not in request.form:
        return jsonify({"status": "error", "message": "缺少文件或需求描述！"}), 400

    # 2. 获取文件和描述
    file = request.files["file"]
    description = request.form["description"]

    try:
        # 3. 读取文件内容
        file_content = file.read()  # 以二进制形式读取

        # 4. 合并数据（将 description 的字符串转成 UTF-8 编码，并与文件内容进行合并）
        combined_data = file_content + description.encode('utf-8')

        # 5. 计算 MD5 值
        md5_hash = hashlib.md5(combined_data).hexdigest()

        # 6. 构造 JSON 响应
        response = {"status": "success",
                    "message": "文件上传成功",
                    "md5": md5_hash}
        return jsonify(response), 200
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
